﻿using Bangle.BLL;
using Bangle.JSONHelpter;
using Bangle.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Sale_SaleEdit : BasePage
{
    private static string FModuleCode = "005001";

    T_Sale model = new T_Sale();
    T_SaleBLL bll = new T_SaleBLL();
    List<T_SaleDetail> list = new List<T_SaleDetail>();
    T_SaleDetailBLL list_bll = new T_SaleDetailBLL();
    T_CustomerBLL customer_bll = new T_CustomerBLL();
    T_ClassificationBLL class_bll = new T_ClassificationBLL();

    #region 属性
    /// <summary>
    /// Guid
    /// </summary>
    public string SaleId
    {
        get
        {
            return Request.QueryString["SaleId"] == null ? "" : Request.QueryString["SaleId"].ToString();
        }
    }

    /// <summary>
    /// Action
    /// </summary>
    public string Action
    {
        get
        {
            return Request.QueryString["Action"] == null ? "" : Request.QueryString["Action"].ToString();
        }
    }

    #endregion

    #region 加载
    protected void Page_Load(object sender, EventArgs e)
    {
        setUserControlStatus();

        if (!IsPostBack)
        {
            BindCustomerDDL();

            GetDataMaster();

            if (Action == "HAdd")
            {
                this.txt_SaleCode.Text = bll.GetNewSaleCode("Sale" + DateTime.Now.ToString("yyyyMMdd"), 4);
                this.txt_Salesman.Text = base.CurrentSession.UserName;
                this.txt_SaleTime.Text = BasePage.GetNowDayString();
            }
        }
    }
    #endregion

    #region 检验用户权限
    private void setUserControlStatus()
    {
        //检验用户权限
        base.CheckUserPermission(FModuleCode);
        this.btn_Modify.Enabled = base.CheckUserPermissionOperation(FModuleCode, "Add");
        this.btn_Save.Enabled = base.CheckUserPermissionOperation(FModuleCode, "Add") || base.CheckUserPermissionOperation(FModuleCode, "Edit");

        this.btn_Modify.Visible = (Action == "Detail");
        this.btn_Save.Visible = (Action == "HAdd" || Action == "Modify");
    }
    #endregion

    #region 获取数据
    private void GetDataMaster()
    {
        if (Action == "Detail" || Action == "HDetail" || Action == "Modify")
        {
            model = bll.GetModel(Guid.Parse(SaleId));
        }
        if (model == null)
        {
            return;
        }
        this.ddl_CustomerId.SelectedValue = model.CustomerId.ToString();
        this.txt_Description.Text = model.Description;
        this.txt_ExchangeRate.Text = model.ExchangeRate.ToString("0.00");
        this.txt_Freight.Text = model.Freight.ToString("0.00");
        this.txt_PayFreight.Text = model.PayFreight.ToString("0.00");
        this.txt_Payment.Text = model.Payment;
        this.txt_SaleCode.Text = model.SaleCode;
        this.txt_Salesman.Text = model.Salesman;
        this.txt_SaleTime.Text = model.SaleTime;
        this.rbl_SaleState.SelectedValue = model.StateId.ToString();

        SetControlStatu();
    }

    private void BindCustomerDDL()
    {
        List<T_Customer> customer_list = customer_bll.GetModelList("Valid=1").OrderBy(o => o.CustomerName).ToList();
        this.ddl_CustomerId.DataValueField = "CustomerId";
        this.ddl_CustomerId.DataTextField = "CustomerName";
        this.ddl_CustomerId.DataSource = customer_list;
        this.ddl_CustomerId.DataBind();

        this.ddl_CustomerId.Items.Insert(0, new ListItem("----请选择----", ""));

        List<T_Classification> salestate_list = class_bll.GetModelListByTypeCode("SaleState");
        this.rbl_SaleState.DataTextField = "ClassificationName";
        this.rbl_SaleState.DataValueField = "ClassificationId";
        this.rbl_SaleState.DataSource = salestate_list;
        this.rbl_SaleState.DataBind();

        this.rbl_SaleState.SelectedIndex = 0;
    }


    private void SetControlStatu()
    {
        bool IsEdit = Action == "HAdd" || Action == "Modify";
        this.ddl_CustomerId.Enabled = IsEdit;
        this.txt_Description.Enabled = IsEdit;
        this.txt_ExchangeRate.Enabled = IsEdit;
        this.txt_Freight.Enabled = IsEdit;
        this.txt_PayFreight.Enabled = IsEdit;
        this.txt_Payment.Enabled = IsEdit;
        this.txt_SaleCode.Enabled = IsEdit;
        this.txt_Salesman.Enabled = IsEdit;
        this.txt_SaleTime.Enabled = IsEdit;
        this.rbl_SaleState.Enabled = IsEdit;

        this.btn_Modify.Visible = (Action == "Detail");
        this.btn_Back.Visible = (Action == "Detail" || Action == "Modify");
    }
    #endregion

    #region 编辑
    protected void btn_Modify_Click(object sender, EventArgs e)
    {
        Response.Redirect(string.Format("SaleEdit.aspx?Action=Modify&SaleId={0}", SaleId));
    }
    #endregion

    #region 提交
    protected void btn_Save_Click(object sender, EventArgs e)
    {
        DataSet ds = bll.GetList(string.Format("SaleCode='{0}' and ltrim(SaleId)<>'{1}'", this.txt_SaleCode.Text.Trim(), SaleId));
        if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
        {
            base.Alert(string.Format("销售单号：【{0}】已存在，请重新输入", this.txt_SaleCode.Text.Trim()));
            return;
        }

        List<T_SaleDetail> list = JSON.parse<List<T_SaleDetail>>(this.hd_GridValue.Value.Trim());

        if (Action == "HAdd")
        {
            if (!base.CheckUserPermissionOperation(FModuleCode, "Add"))
            {
                base.Alert("没有操作权限，请联系管理员!");
                return;
            }
            model = new T_Sale();
        }
        else if (Action == "Modify")
        {
            if (!base.CheckUserPermissionOperation(FModuleCode, "Edit"))
            {
                base.Alert("没有操作权限，请联系管理员!");
                return;
            }
            model = bll.GetModel(Guid.Parse(SaleId));
            if (model == null)
            {
                base.Alert("操作出现异常，请联系管理员");
                return;
            }
        }

        model.CustomerId = Guid.Parse(this.ddl_CustomerId.SelectedValue);
        model.Description = this.txt_Description.Text.Trim();
        model.ExchangeRate = Convert.ToDecimal(this.txt_ExchangeRate.Text.Trim());
        model.Freight = Convert.ToDecimal(this.txt_Freight.Text.Trim());
        model.PayFreight = Convert.ToDecimal(this.txt_PayFreight.Text.Trim());
        model.Payment = this.txt_Payment.Text.Trim();
        model.SaleCode = this.txt_SaleCode.Text.Trim();
        model.Salesman = this.txt_Salesman.Text.Trim();
        model.SaleTime = this.txt_SaleTime.Text.Trim();
        model.StateId = Convert.ToInt32(this.rbl_SaleState.SelectedValue);
        model.UpdateTime = BasePage.GetNowTimeString();
        model.UpdateUserId = BasePage.CurrentSession2.UserID;

        try
        {
            if (Action == "HAdd")
            {
                model.SaleId = Guid.NewGuid();
                model.CreateTime = model.UpdateTime;
                model.CreateUserId = model.CreateUserId;
                model.Valid = 1;
                bll.Add(model);
            }
            else
            {
                bll.Update(model);
            }

            //Delete 数据
            string sDeleteSqlString = "''";
            foreach (T_SaleDetail item in list)
            {
                sDeleteSqlString += ",'" + item.SaleDetailId.ToString() + "'";
            }
            list_bll.Delete(" ltrim(SaleDetailId) not in (" + sDeleteSqlString + ")");

            foreach (T_SaleDetail item in list)
            {
                item.SaleId = model.SaleId;
                if (item.SaleDetailId == Guid.Empty)
                {
                    item.SaleDetailId = Guid.NewGuid();
                    item.CreateTime = BasePage.GetNowTimeString();
                    list_bll.Add(item);
                }
                else
                {
                    list_bll.Update(item);
                }
            }
        }
        catch (Exception ex)
        {
            base.AlertError("操作出现异常，请联系系统管理员！", ex.ToString());
            return;
        }

        if (Action == "HAdd")
        {
            //Response.Redirect(string.Format("SaleEdit.aspx?Action=HDetail&SaleId={0}", model.SaleId.ToString()));
            base.Redirect("操作成功", string.Format("SaleEdit.aspx?Action=HAdd"));
        }
        else if (Action == "Modify")
        {
            base.CloseWindowAndRefresh();
        }
    }
    #endregion

    #region Ajex获取列表数据
    [WebMethod]
    public static AjexResponseModel GetGridDataHtml(int pageSize, int pageIndex, string OrderField, string QueryString, string SaleId, int IsEdit)
    {
        AjexResponseModel response = new AjexResponseModel();

        string swhere = string.Format(" SaleId='{0}' ", SaleId);

        #region 获取数据
        DataTable dt = null;
        int pCount = 0;
        try
        {
            UtilityBLL ubll = new UtilityBLL();
            dt = ubll.GetListByPage("T_SaleDetail", "*", "PurchaseCode", swhere, pageSize, pageIndex, 1, out pCount);

            #region 生成HTML
            StringBuilder sHtmlString = new StringBuilder();

            string sHtmlModel = "";
            string sControl = "";

            if (IsEdit == 1)
            {
                sHtmlModel = @"
                    <tr {0} data-SaleDetailId='{1}'>
                        <td class='edit-td' date-filedname='PurchaseCode'><input type='text' value='{3}' /></td>
                        <td class='edit-td' date-filedname='SupplierName'><input type='text' value='{7}' /></td>
                        <td class='edit-td' date-filedname='PurchaseTime'><input type='text' value='{2}' class='Wdate' onfocus='WdatePicker()'/></td>
                        <td class='edit-td' date-filedname='PurchaseReceipt'><input type='text' value='{6}' /></td>
                        <td class='edit-td' date-filedname='Quantity'><input type='text' value='{4}' onchange='onQuantityChange(this)' /></td>
                        <td class='edit-td' date-filedname='PurchasePrice'><input type='text' value='{5}' onchange='onPurchasePriceChange(this)' /></td>
                        <td date-filedname='PurchaseAmount' style='text-align:right;'><span>0</span></td>
                        <td class='edit-td' date-filedname='SalePriceRMB'><input type='text' value='{8}' onchange='onSalePriceRMBChange(this)' /></td>
                        <td class='edit-td' date-filedname='SalePriceUSD'><input type='text' value='{9}' onchange='onSalePriceUSDChange(this)' /></td>
                        <td date-filedname='SaleAmountRMB' style='text-align:right;'><span>0</span></td>
                        <td date-filedname='SaleAmountUSD' style='text-align:right;'><span>0</span></td>
                        <td date-filedname='SaleProfitRMB' style='text-align:right;'><span>0</span></td>
                        <td>{10}</td>
                    </tr>
                ";

                sControl = "<a href='javascript:void()' onclick='delGridRow(this)'>删除</a>";
            }
            else
            {
                sHtmlModel = @"
                    <tr {0} data-SaleDetailId='{1}'>
                        <td class='edit-td' date-filedname='PurchaseCode'><input type='text' value='{3}' disabled='disabled'/></td>
                        <td class='edit-td' date-filedname='SupplierName'><input type='text' value='{7}' disabled='disabled'/></td>
                        <td class='edit-td' date-filedname='PurchaseTime'><input type='text' value='{2}' disabled='disabled'/></td>
                        <td class='edit-td' date-filedname='PurchaseReceipt'><input type='text' value='{6}' disabled='disabled'/></td>
                        <td class='edit-td' date-filedname='Quantity'><input type='text' value='{4}' disabled='disabled'/></td>
                        <td class='edit-td' date-filedname='PurchasePrice'><input type='text' value='{5}' disabled='disabled'/></td>
                        <td date-filedname='PurchaseAmount' style='text-align:right;'><span>0</span></td>
                        <td class='edit-td' date-filedname='SalePriceRMB'><input type='text' value='{8}' disabled='disabled'/></td>
                        <td class='edit-td' date-filedname='SalePriceUSD'><input type='text' value='{9}' disabled='disabled'/></td>
                        <td date-filedname='SaleAmountRMB' style='text-align:right;'><span>0</span></td>
                        <td date-filedname='SaleAmountUSD' style='text-align:right;'><span>0</span></td>
                        <td date-filedname='SaleProfitRMB' style='text-align:right;'><span>0</span></td>
                        <td>{10}</td>
                    </tr>
                ";

                sControl = "";
            }

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                sHtmlString.Append(string.Format(sHtmlModel
                    , (i % 2 == 0 ? "" : "class='ht-grid-even'")
                    , dt.Rows[i]["SaleDetailId"].ToString()
                    , dt.Rows[i]["PurchaseTime"].ToString()
                    , dt.Rows[i]["PurchaseCode"].ToString()
                    , Convert.ToDecimal(dt.Rows[i]["Quantity"].ToString()).ToString("0.00")
                    , Convert.ToDecimal(dt.Rows[i]["PurchasePrice"].ToString()).ToString("0.00")
                    , dt.Rows[i]["PurchaseReceipt"].ToString()
                    , dt.Rows[i]["SupplierName"].ToString()
                    , Convert.ToDecimal(dt.Rows[i]["SalePriceRMB"].ToString()).ToString("0.00")
                    , Convert.ToDecimal(dt.Rows[i]["SalePriceUSD"].ToString()).ToString("0.00")
                    , sControl
                    ));
            }
            #endregion

            response.gridHtml = sHtmlString.ToString();
            response.recordCound = pCount;
            response.pageIndex = pageIndex;
            response.pageSize = pageSize;// BasePage.CurrentSession2.PageSize;
        }
        catch (Exception ex)
        {
            response.msg = ex.ToString();
        }
        #endregion

        return response;
    }

    #endregion
}

